package com.xgggh.redpack;

import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Toast;

import com.xgggh.app.RxBaseActivity;
import com.xgggh.redpack.databinding.ActivityCameraBinding;

import cn.bingoogolapple.qrcode.core.QRCodeView;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_CONTACTS;

/**
 * @title  二维码扫描
 */
public class CameraActivity extends RxBaseActivity  implements QRCodeView.Delegate{

    ActivityCameraBinding mBinding;
    private final int REQUEST_CAMERA=0x120;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding= DataBindingUtil.setContentView(this,R.layout.activity_camera);
        setSupportActionBar(mBinding.toolBarParent.toolbar);
        mBinding.contentCamera.scanner.setDelegate(this);
    }





    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startScan();
            }
        }
    }


    private void startScan(){
        //打开相机
        mBinding.contentCamera.scanner.startCamera();
        //显示扫码框
        mBinding.contentCamera.scanner.showScanRect();
        //开始扫码
        mBinding.contentCamera.scanner.startSpot();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
       Snackbar.make(this.getWindow().getDecorView(),"你获得10元激励红包，是否打开",Snackbar.LENGTH_LONG).show();
        vibrate();
        mBinding.contentCamera.scanner.startSpot();
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.makeText(this, "打开相机出错", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mayRequestPermissions(CAMERA,REQUEST_CAMERA)) {
            startScan();
        }
    }

    @Override
    protected void onStop() {
        mBinding.contentCamera.scanner.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mBinding.contentCamera.scanner.onDestroy();
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }



}
